#include "widget.h"
#include "ui_widget.h"
#include <QFileDialog>
#include <QDebug>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    server = new SimServer(this);
    cur = 0;
    angle = 0;
    dInfo.speed = 0;
    dInfo.acce = 0;
    dInfo.brake = 0;
    dInfo.dir = 0;
    dInfo.lightFlag = "N";
    dInfo.parking_brake = "TRUE";
    dInfo.drive_mode = "MANU";
    QString str("#12#OK#f06bed7b");
    qDebug()<<QString::number(JQChecksum::crc32(str.toLocal8Bit()), 16);

    connect(&posTime, SIGNAL(timeout()), this, SLOT(posTimeout()));
    connect(&infoTime, SIGNAL(timeout()), this, SLOT(infoTimeout()));
    connect(server, SIGNAL(newState(bool)), this, SLOT(socketStateChanged(bool)));
    connect(server, SIGNAL(newData(QString)), this, SLOT(recvData(QString)));
}

Widget::~Widget()
{
    delete ui;
}

void Widget::socketStateChanged(bool connected)
{
    ui->state->setChecked(connected);
}

void Widget::posTimeout()
{
    if(cur>=vPos.count())
        cur=0;

    simPos(vPos[cur]);
    cur++;
}

void Widget::infoTimeout()
{
    simInfo(dInfo);
}

void Widget::recvData(QString _data)
{
    qDebug()<<"recvData"<<_data;
    QStringList parList = _data.split("#", QString::SkipEmptyParts);
    QString checkSum= parList.at(0).toUpper();
    int checkPos = _data.indexOf("#",1);
    if(checkPos == -1)
        return;

    QByteArray qba = _data.right(_data.length() - checkPos).toLocal8Bit();
    QString localCheckSum = QString::number(JQChecksum::crc32(qba),16).toUpper();
    if(localCheckSum != checkSum)
    {
        qDebug()<<"[recvData]"<<"checkSum error.";
        qDebug()<<localCheckSum<<checkSum;
        return;
    }

    if(parList.at(2) == QString("GOTO"))
    {
        ui->target->setText(QString("%1 %2 %3").arg(parList.at(3)).arg(parList.at(4)).arg(5));
    }

}

void Widget::on_open_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(NULL, "请打开模拟坐标文件", "/home/xyzn/gitee/xingyun/XingYun_V1/testData/");
    if(fileName.isNull())
        return;

    readPoints(fileName);
    ui->lineEdit->setText(fileName);
    qDebug()<<"read points:"<<vPos.count();
}

void Widget::readPoints(QString posFile)
{
    QFile f(posFile);
    f.open(QFile::ReadOnly);
    QByteArray qba;

    while(!(qba = f.readLine()).isEmpty())
    {
        QString str = QString(qba);
        qDebug()<<"[readPoint]"<<str;
        QStringList l = str.split(" ", QString::SkipEmptyParts);
        if(l.count() != 2)
        {
            qDebug()<<"[readPoint]:File fomat error.";
            return;
        }
        bool ok;
        QPointF p;
        p.setX(l.at(0).toDouble(&ok));
        if(!ok)
        {
            qDebug()<<"[readPoint]:File fomat error.";
            return;
        }
        p.setY(l.at(1).toDouble(&ok));
        if(!ok)
        {
            qDebug()<<"[readPoint]:File fomat error.";
            return;
        }

        vPos.push_back(p);
    }
    f.close();

}

void Widget::simPos(QPointF pos)
{
    QString params = QString(",POS,%1,%2,%3,%4,%5").arg(QString::number(pos.x(), 'f')).arg(QString::number(pos.y(), 'f')).arg(angle).arg("MOVE").arg("OK");
    QString strPack = QString(",%1%2").arg(params.length()).arg(params);
    strPack = QString("#%1").arg(QString::number(JQChecksum::crc32(strPack.toLocal8Bit()), 16)) + strPack;
    qDebug()<<"[simGoto]"<<strPack;
    server->writeData(strPack);
}

void Widget::simInfo(DriveInfo info)
{
    QString params = QString(",CARINFO,%1,%2,%3,%4,%5,%6,%7").arg(info.speed).arg(info.acce).arg(info.brake).arg(info.dir).arg(info.drive_mode).arg(info.parking_brake).arg(info.lightFlag);
    QString strPack = QString(",%1%2").arg(params.length()).arg(params);
    strPack = QString("#%1").arg(QString::number(JQChecksum::crc32(strPack.toLocal8Bit()), 16)) + strPack;
    qDebug()<<"[siminfo]"<<strPack;
    server->writeData(strPack);
}

void Widget::on_start_clicked(bool checked)
{
    if(checked)
    {
        ui->start->setText("停止");
        posTime.start(30);
    }
    else
    {
        ui->start->setText("开始");
        posTime.stop();
//        cur = 0;
    }
}

void Widget::on_angle_valueChanged(int value)
{
    angle = (double)value+0.1;
}

void Widget::on_speed_valueChanged(int value)
{
    dInfo.speed = value;
}

void Widget::on_acce_valueChanged(int value)
{
    dInfo.acce = value;
}

void Widget::on_brake_valueChanged(int value)
{
    dInfo.brake = value;
}

void Widget::on_gar_valueChanged(int value)
{
    dInfo.dir = value;
}

void Widget::on_drive_mode_clicked(bool checked)
{
    dInfo.setDriveMode(checked);
//    dInfo.drive_mode = checked;
}

void Widget::on_parking_brake_clicked(bool checked)
{
    dInfo.setParkingBrake(checked);
//    dInfo.parking_brake = checked;
}

void Widget::on_light_r_clicked(bool checked)
{
    if(checked)
    {
        dInfo.setLightFlag(DriveInfo::L_R);
//        dInfo.lightFlag = DriveInfo::L_R;
    }
}

void Widget::on_light_g_clicked(bool checked)
{
    if(checked)
    {
        dInfo.setLightFlag(DriveInfo::L_G);
    }
}

void Widget::on_light_y_clicked(bool checked)
{
    if(checked)
    {
        dInfo.setLightFlag(DriveInfo::L_Y);
    }
}

void Widget::on_sim_start_toggled(bool checked)
{
    if(checked)
    {
        infoTime.start(1000);
    }
    else
    {
        infoTime.stop();
    }
}


void Widget::on_light_null_clicked(bool checked)
{
    if(checked)
    {
        dInfo.setLightFlag(DriveInfo::L_N);
    }
}
